<template>
  <d2-container>
    <el-card class="selectFrom">
      <el-form :inline="true" :model="selectFrom" class="demo-form-inline" size="mini">
        <el-form-item label="角色名称">
          <el-input v-model="selectFrom.name" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTable()">查询</el-button>
          <el-button type="primary" @click="addFrom()">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="tableFrom">
      <el-table :data="tableData" border style="width: 100%" size="mini" :height="height">
        <el-table-column prop="id" label="角色id" align="center">
        </el-table-column>
        <el-table-column prop="name" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="addRoleMenu(scope.row)">分配菜单</el-button>
            <el-button type="primary" size="mini" @click="updateFrom(scope.row)">修改</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="deleteFrom(scope.row)">
              <el-button slot="reference" type="danger" size="mini" style="margin-left:10px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[10, 15, 20, 25]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :title="title" :visible.sync="sign" width="30%" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <el-form ref="form" :model="form" label-width="80px" :rules="rule" size="mini">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFrom()" size="mini">取 消</el-button>
        <el-button type="primary" @click="submit()" size="mini" v-loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配菜单" :visible.sync="roleMenuSign" width="30%" :close-on-click-modal="false">
      <el-tree 
        :data="menuList" 
        ref="tree" 
        :props="{
          label: 'title',
          children: 'children'
          }" 
        show-checkbox 
        node-key="id" 
        :default-checked-keys="checkMenu" 
        :default-expand-all="true"
        :check-strictly="true">
        </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTree()" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitTree()" size="mini" v-loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>
<script>
import { getInfoList } from "@/api/tSystemMenu.js"
import { getInfoById,addInfoRoleMenu } from "@/api/tRoleMenu.js"
import { addInfo, deleteInfo, updateInfo, pageInfo } from "@/api/tSystemRole.js"
export default {
  name: 'tSystemRole',
  data() {
    return {
      roleMenu: {},//角色对象
      checkMenu: [],//选中菜单
      menuList: [],//菜单结构
      roleMenuSign: false,
      height: window.innerHeight - 350, //表格高度
      loading: false,//提交
      sign: false,
      selectFrom: {},//查询条件
      page: 1,
      total: 0,
      limit: 10,
      tableData: [],//数据
      form: {},//表单
      isUpdate: false,//是否修改
      title: "新增角色管理", rule: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {
    //-------------------------表格响应----------------//
    this.createHeight();
    //当页面发生变化时，表格高度固定
    window.onresize = () => {
      return (() => {
        this.$nextTick(() => {
          this.createHeight();
        });
      })();
    };
    this.getTable();
  },
  methods: {
    async submitTree() {
      await addInfoRoleMenu({
        roleId: this.roleMenu.id,
        menuIds: this.getMenIds()
      })
      this.closeTree();
    },
    getMenIds(){
      let menus = this.$refs.tree.getCheckedNodes();
      let menuIds = [];
      menus.forEach(item=>{
        menuIds.push(item.id);
      })
      return menuIds;
    },
    closeTree() {
      this.roleMenuSign = false;
    },
    //添加用户菜单
    addRoleMenu(item) {
      this.roleMenu = item;
      this.roleMenuSign = true;
      getInfoList({}).then(res => {
        this.menuList = res.dataList;
      })
      getInfoById({ roleId: item.id }).then(res => {
        let dataList = res.data;
        let datas = [];
        dataList.forEach(item => {
          datas.push(item.menuId)
        });
        this.$refs['tree'].setCheckedKeys(datas);
      })
    },
    //添加表单
    addFrom() {
      this.sign = true;
      this.isUpdate = false;
      this.title = "新增角色管理";
    },
    //修改表单
    updateFrom(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.sign = true;
      this.isUpdate = true;
      this.title = "修改角色管理";
    },
    //删除表单
    deleteFrom(row) {
      deleteInfo(row).then(res => {
        this.getTable();
      })
    },
    //关闭表单
    closeFrom() {
      this.sign = false;
      this.loading = false;
      this.form = {};
      if (this.$refs['form']) {
        this.$refs['form'].resetFields();
      }
    },
    //提交表单
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.isUpdate) {
            updateInfo(this.form).then(res => {
              this.closeFrom();
              this.getTable();
            })
          } else {
            addInfo(this.form).then(res => {
              this.closeFrom();
              this.getTable();
            })
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 获取表格数据
     */
    getTable() {
      this.selectFrom.page = this.page;
      this.selectFrom.limit = this.limit;
      pageInfo(this.selectFrom).then(res => {
        console.log(res);
        this.tableData = res.dataList;
        this.total = res.total;
      })
    },
    //改变条数
    handleSizeChange(val) {
      this.limit = val;
      this.getTable();
    },
    //改变页数
    handleCurrentChange(val) {
      this.page = val;
      this.getTable();
    },
    //---------------自动变更表格高度------------------//
    createHeight() {
      this.height = window.innerHeight - 350;
    }
  }
}
</script>
<style scoped>
.selectFrom {
  margin: 5px;
  height: 80px;
}

.tableFrom {
  margin: 5px;
  height: 600px;
}

.block {
  text-align: center;
}
</style>
